﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DatabaseAdminTools.Connections;

namespace DatabaseAdminTools.OptionForms
{
    public partial class TableTab : UserControl
    {
        #region Variables
        private SqlTable table = null;
        private DataTable data;
        private bool[] updateNeeded;

        private CheckBox[] columnCheckBoxs;

        public bool save = true;
        #endregion

        #region Initial form and data
        public TableTab(Connection con, String tbName)
        {
            InitializeComponent();
            String[] str = tbName.Split('@');
            table = new SqlTable(con, str[0], str[1]);
            table.setValues();
            setData();
        }

        private void setData()
        {
            data = table.Data;
            if (data != null)
            {
                dataGridView1.DataSource = data;
                int cols = data.Columns.Count;
                // column show / hide
                columnCheckBoxs = new CheckBox[cols];
                for (int i = 0; i < cols; i++)
                {
                    addColumnCheckBoxs(table.Columns[i], i);
                }
                int rows = data.Rows.Count;
                // update needed
                updateNeeded = new bool[rows];
                for (int i = 0; i < rows; i++)
                {
                    updateNeeded[i] = false;
                }
                toolStripComboBox1.Items.Add("All");
                // search Combo Box
                foreach (DataColumn col in data.Columns)
                {
                    toolStripComboBox1.Items.Add(col.ColumnName);
                }
                toolStripComboBox1.SelectedIndex = 0;
                // disable sort mode;
                foreach (DataGridViewColumn col in dataGridView1.Columns)
                {
                    col.SortMode = DataGridViewColumnSortMode.NotSortable;
                }
            }

        }
        #endregion

        #region dataGridView Event
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < updateNeeded.Length)
            {
                updateNeeded[e.RowIndex] = true;
            }
            save = false;
            savedStateLabel.Text = "Table UNSAVED";
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            var cells = dataGridView1.SelectedCells;
            if (cells.Count > 0)
            {
                selectedRowLabel.Visible = true;
                selectedRowLabel.Text = "row " + (cells[0].RowIndex + 1) + " of " + dataGridView1.RowCount;
            }
            else
            {
                selectedRowLabel.Visible = false;
            }
        }

        #region DataGridView Context Menu Trip Event
        private void columnsShowedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel2Collapsed = !columnsShowedToolStripMenuItem.Checked;
            showHideColumnsToolStripMenuItem.Checked = columnsShowedToolStripMenuItem.Checked;
        }

        private void showHideColumnsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel2Collapsed = !showHideColumnsToolStripMenuItem.Checked;
            columnsShowedToolStripMenuItem.Checked = showHideColumnsToolStripMenuItem.Checked;
        }

        private void showHideToolStripMenuItem_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel2Collapsed = true;
            columnsShowedToolStripMenuItem.Checked = false;
            showHideColumnsToolStripMenuItem.Checked = false;
        }

        private void addColumnCheckBoxs(string Text, int num)
        {
            columnCheckBoxs[num] = new System.Windows.Forms.CheckBox();
            columnCheckBoxs[num].AutoSize = true;
            columnCheckBoxs[num].Checked = true;
            columnCheckBoxs[num].Location = new System.Drawing.Point(15, 36 + (25 * num));
            columnCheckBoxs[num].Name = Text;
            columnCheckBoxs[num].Size = new System.Drawing.Size(80, 17);
            columnCheckBoxs[num].TabIndex = 1;
            columnCheckBoxs[num].Text = Text;
            columnCheckBoxs[num].UseVisualStyleBackColor = true;
            this.splitContainer1.Panel2.Controls[0].Controls.Add(columnCheckBoxs[num]);
            columnCheckBoxs[num].CheckedChanged += new System.EventHandler(checkChanged);
        }

        private void checkChanged(object sender, EventArgs e)
        {
            foreach (var cbox in columnCheckBoxs)
            {
                showHideColumn(cbox.Checked, cbox.Name);
            }
        }

        private void showHideColumn(bool show, String columnName)
        {
            dataGridView1.Columns[columnName].Visible = show;
        }

        private void dataGridViewContextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            var rows = dataGridView1.SelectedRows;
            toolStripSeparator25.Visible = deleteSelectedRowsToolStripMenuItem.Visible = (rows.Count > 0);
        }

        private void deleteSelectedRowsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            deleteSelectedRows();
        }

        private void deleteSelectedRows()
        {
            var rows = dataGridView1.SelectedRows;
            if (rows.Count > 0)
            {
                Save();
                DialogResult result = MessageBox.Show(this, "Do you want to DELETE " + rows.Count + " selected rows ?",
                        "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    foreach (DataGridViewRow row in rows)
                    {
                        try
                        {
                            if (table.deleteRecord(row) == 1)
                            {
                                dataGridView1.Rows.Remove(row);
                            }
                            else
                            {
                                MessageBox.Show(this, "Error while delete row !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                deleteSelectedRows();
            }
        }
        #endregion
        #endregion

        private void Save()
        {
            this.Cursor = Cursors.WaitCursor;
            update();
            save = true;
            savedStateLabel.Text = "Table saved";
            this.Cursor = Cursors.Default;
        }

        private void update()
        {
            int rows = updateNeeded.Length;
            for(int i = 0; i < rows; i++)
            {
                if (updateNeeded[i])
                {
                    DataRow newValRow = data.Rows[i];
                    try
                    {
                        table.update(i, newValRow);
                        updateNeeded[i] = false;
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        DataRow oldVal = table.getRow(i);
                        for (int j = 0; j < table.Columns.Length; j++)
                        {
                            data.Rows[i][j] = oldVal[j];
                        }
                    }
                }
            }
        }

        #region other controls event
        private void saveButton_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void setToNULLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var cell = dataGridView1.SelectedCells[0];
            cell.Value = null;
        }
        #endregion

        #region search
        private void searchTextBox_Enter(object sender, EventArgs e)
        {
            if (searchTextBox.Text.Equals("Type here to search"))
            {
                searchTextBox.Text = "";
            }
        }

        private void searchTextBox_Leave(object sender, EventArgs e)
        {
            if (searchTextBox.Text.Equals(""))
            {
                searchTextBox.Text = "Type here to search";
            }
        }

        private void findToolStripMenuItem_Click(object sender, EventArgs e)
        {
            searchTextBox.Focus();
            if (searchTextBox.Text.Equals(""))
            {
                searchTextBox.Text = "Type here to search";
            }
            searchTextBox.SelectAll();
        }
        #endregion

        #region Toolstripdownbutton event (search options)

        private void exactlyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            approximateSearchToolStripMenuItem.Checked = false;
        }

        private void approximateSearchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            exactlyToolStripMenuItem.Checked = false;
        }

        private void resultInCurrentTabToolStripMenuItem_Click(object sender, EventArgs e)
        {
            resultInNewTabToolStripMenuItem.Checked = false;
        }

        private void resultInNewTabToolStripMenuItem_Click(object sender, EventArgs e)
        {
            resultInCurrentTabToolStripMenuItem.Checked = false;
        }

        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            searchTextBox.Focus();
        }

        #endregion

        #region close event
        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            closeTab();
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            closeTab();
        }

        public bool closeTab()
        {
            bool close = true;
            if (!save)
            {
                DialogResult result = MessageBox.Show("Table "+table.ToString()+" unsaved. Do you want to save your changes ?",
                    "Confirm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    Save();
                }
                else if (result == DialogResult.Cancel)
                {
                    close = false;
                }
            }
            if (close)
            {
                ((TableForm)this.ParentForm).removeTab(table.ToString());
                this.Dispose(true);
            }
            return close;
        }

        #endregion

        private void toolStripButton6_Click(object sender, EventArgs e)
        {

        }

    }
}
